﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace WorkerRole
{
    public class LogDataContext : TableServiceContext
    {
        public const string ErrorLogTable = "ErrorLogs";
        public const string EventLogTable = "EventLogs";

        public LogDataContext()
            : base(CloudStorageAccount.FromConfigurationSetting("DataConnectionString").TableEndpoint.ToString(),
                    CloudStorageAccount.FromConfigurationSetting("DataConnectionString").Credentials)
        {
            Init();
        }

        public LogDataContext(string baseAddress, StorageCredentials credentials)
            : base(baseAddress, credentials)
        {
        }

        private static bool initalized = false;
        static void Init()
        {
            if (!initalized)
            {

                var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                CloudTableClient.CreateTablesFromModel(typeof(LogDataContext), account.TableEndpoint.AbsoluteUri, account.Credentials);

                initalized = true;

            }

        }

        public IQueryable<ErrorLog> ErrorLogs
        {
            get
            {
                return this.CreateQuery<ErrorLog>(ErrorLogTable);
            }
        }

        public IQueryable<EventLog> EventLogs
        {
            get
            {
                return this.CreateQuery<EventLog>(EventLogTable);
            }
        }

        public void SaveError(string description)
        {
            this.SaveError(description, string.Empty, System.DateTime.Now);
        }

        public void SaveError(string description, string remarks)
        {
            this.SaveError(description, remarks, System.DateTime.Now);
        }

        public void SaveError(string description, string remarks, DateTime errorTime)
        {
            this.AddObject(ErrorLogTable, new ErrorLog { Description = description, ErrorTime = errorTime, Remarks = remarks });
            this.SaveChanges();
        }

        public void SaveEvent(string description)
        {
            this.SaveEvent(description, string.Empty, System.DateTime.Now);
        }

        public void SaveEvent(string description, string remarks)
        {
            this.SaveEvent(description, remarks, System.DateTime.Now);
        }

        public void SaveEvent(string description, string remarks, DateTime errorTime)
        {
            this.AddObject(EventLogTable, new EventLog { Description = description, EventTime = errorTime, Remarks = remarks });
            this.SaveChanges();
        }
    }
}
